package com.macbulldev.poc.testgin.controller;

import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.PolicyForm;
import com.macbulldev.poc.testgin.domain.Scenario;
import com.macbulldev.poc.testgin.domain.StateOrProvince;
import com.macbulldev.poc.testgin.domain.TrialGroup;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "policyform", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.PolicyForm.class)
@org.springframework.web.bind.annotation.RequestMapping("/policyform/**")
@org.springframework.stereotype.Controller
public class PolicyFormController {
	
	private static final Logger LOGGER = Logger.getLogger(PolicyForm.class);
	
	@RequestMapping(value = "/policyform/list", method = RequestMethod.GET)    
    public String renderPolicyFormList(@RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {    
		
		int sizeNo = 100;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        modelMap.addAttribute("policyforms",PolicyForm.findPolicyFormEntries(pageNumber*sizeNo, sizeNo));            
        Long count = PolicyForm.countPolicyForms();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        return "policyform/list";        
    }
	
	@RequestMapping(value = "/policyform/filter", method = RequestMethod.GET)    
    public String renderPolicyFormList(@RequestParam(value = "stateOrProvince", required = false) Long stateOrProvinceId,ModelMap modelMap) {    
		
		int sizeNo = 100;
		Integer page = null;
        int pageNumber= page == null ? 0 : page;
        
        if(stateOrProvinceId == 0)
        {
        	 modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	 modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
             modelMap.addAttribute("policyforms",PolicyForm.findPolicyFormEntries(pageNumber*sizeNo, sizeNo));            
             Long count = PolicyForm.countPolicyForms();
             modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        else
        {
        	modelMap.addAttribute("stateorprovince",stateOrProvinceId);
        	modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        	Set<PolicyForm> policyforms = null;
        	policyforms = StateOrProvince.findStateOrProvince(stateOrProvinceId).getPolicyForms();
            modelMap.addAttribute("policyforms",policyforms);
            Long count = Long.valueOf(policyforms.size());
            modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        }
        
        return "policyform/list";        
    }


	@RequestMapping(value = "/policyform", method = RequestMethod.POST)    
    public String create(@Valid PolicyForm policyForm, BindingResult result, ModelMap modelMap, HttpSession session ) {    
        if (policyForm == null) throw new IllegalArgumentException("A policyForm is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("policyForm", policyForm);            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            return "policyform/create";            
        }
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        policyForm.setCreateUsername("admin");
        policyForm.setUpdateUsername(sessionUser.getName());
        policyForm.setCreateTs(new Date());
        policyForm.setUpdateTs(new Date());
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(PolicyForm.class.getSimpleName());
    	log.setOperation(policyForm.getStateOrProvince().getCode()+":  "+ policyForm.getDisplayName()+" Created");
    	log.persist();
        
        
        policyForm.persist();        
        return "redirect:/policyform/" + policyForm.getId();        
    }

	@RequestMapping(value = "/policyform/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("policyForm", new PolicyForm());        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios()); 
        modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces()); 
        return "policyform/create";        
    }

	@RequestMapping(value = "/policyform/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("policyForm", PolicyForm.findPolicyForm(id));        
        return "policyform/show";        
    }

	@RequestMapping(value = "/policyform", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("policyforms", PolicyForm.findPolicyFormEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) PolicyForm.countPolicyForms() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("policyforms", PolicyForm.findAllPolicyForms());            
        }        
        return "policyform/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid PolicyForm policyForm, BindingResult result, ModelMap modelMap, HttpSession session ) {    
        if (policyForm == null) throw new IllegalArgumentException("A policyForm is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("policyForm", policyForm);            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            return "policyform/update";            
        }
        
        PolicyForm pf = PolicyForm.findPolicyForm(policyForm.getId());
        
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        policyForm.setUpdateUsername(sessionUser.getName());
        policyForm.setCreateUsername(pf.getCreateUsername());
        policyForm.setCreateTs(pf.getCreateTs());
        policyForm.setUpdateTs(new Date());
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(PolicyForm.class.getSimpleName());
    	log.setOperation("PolicyForm "+ policyForm.getDisplayName()+" Updated");
    	log.persist();
    	
    	for(Scenario s : pf.getStateOrProvince().getScenarios())
        {
        	for(TrialGroup tg : s.getTrialGroups())
        	{
        		for(PolicyForm tgpf : tg.getPolicyForms())
        		{
        			if(tgpf.getDisplayName().equalsIgnoreCase(pf.getDisplayName()) && tgpf.getImportName().equalsIgnoreCase(pf.getImportName()) && tgpf.getAbbrName().equalsIgnoreCase(pf.getAbbrName()))
        			{
        				tgpf.setDisplayName(policyForm.getDisplayName());
        				tgpf.setAbbrName(policyForm.getAbbrName());
        				tgpf.setImportName(policyForm.getImportName());
        				tgpf.merge();
        			}
        		}
        			
        	}
        	
        }
        
        
        policyForm.merge();        
        return "redirect:/policyform/" + policyForm.getId();        
    }

	@RequestMapping(value = "/policyform/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("stateorprovinces",StateOrProvince.findAllStateOrProvinces());
        modelMap.addAttribute("policyForm", PolicyForm.findPolicyForm(id));        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        return "policyform/update";        
    }
	
	@Transactional
	@RequestMapping(value = "/policyform/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
       
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(PolicyForm.class.getSimpleName());
    	log.setOperation(PolicyForm.findPolicyForm(id).getStateOrProvince().getCode()+":  "+PolicyForm.findPolicyForm(id).getDisplayName()+" Deleted");
    	log.persist();
    	
    	PolicyForm pf = PolicyForm.findPolicyForm(id);
    	
    	for(Scenario s : pf.getStateOrProvince().getScenarios())
        {
        	for(TrialGroup tg : s.getTrialGroups())
        	{
        		for(PolicyForm tgpf : tg.getPolicyForms())
        		{
        			if(tgpf.getDisplayName().equalsIgnoreCase(pf.getDisplayName()) && tgpf.getImportName().equalsIgnoreCase(pf.getImportName()) && tgpf.getAbbrName().equalsIgnoreCase(pf.getAbbrName()))
        			{
        				
        				LOGGER.error("Trying to Delete PolicyForm:  "+tgpf.getImportName()+" :  "+tgpf.getId());
        				
        				PolicyForm.deletePolicyFormByTrialGroup(tgpf);
        				//PolicyForm.findPolicyForm(tgpf.getId()).remove();
        			}
        		}
        			
        	}
        	
        }
    	
        
        PolicyForm.findPolicyForm(id).remove();
        
 
        return "redirect:/policyform?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
}
